package com.gmom.tako;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.gmom.tako.db.DbAccessor;
import com.gmom.tako.model.Url;
import com.gmom.tako.network.RssGetter;

public class RssUrlAdditionTask extends AsyncTask<String, Void, Boolean>{
	private Context context;
	private AsyncTaskProgress progress;
	public RssUrlAdditionTask(AsyncTaskProgress progress,Context context) {
		this.context = context;
		this.progress = progress;
	}
	@Override
	protected Boolean doInBackground(String... params) {
		DbAccessor db = new DbAccessor();
		RssGetter getter = RssGetter.getInstance();
		Boolean result = true;
		for (String url : params) {
			if (url.matches("^(https?)(:\\/\\/[-_.!~*\\'()a-zA-Z0-9;\\/?:\\@&=+\\$,%#]+)$")) {
				HashMap<String, String> data = getter.parseMetadata(url);
				Url u = new Url();
				u.setUrl(url);
				u.setTitle(data.get("title"));
				if (u.getTitle().equals(""))
					result = false;
				else 
					db.insertUrl(context, u);
			} else {
				result = false;
			}
		}
		return result;
	}
	
	@Override
	protected void onPostExecute(Boolean p) {
		if (p) {
			Toast.makeText(context, "追加完了", Toast.LENGTH_LONG).show();
			progress.onComplete(null);
		} else {
			Toast.makeText(context, "追加失敗", Toast.LENGTH_LONG).show();
		}
			
	}
}
